<template>
  <div class="advance-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户/供应商">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户或供应商名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.billType" placeholder="请选择类型" clearable>
            <el-option label="预收款" value="receipt" />
            <el-option label="预付款" value="payment" />
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择付款方式" clearable>
            <el-option label="现金" value="cash" />
            <el-option label="银行" value="bank" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信" value="wechat" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总预收金额</div>
            <div class="stats-value">¥{{ stats.totalReceiptAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总预付金额</div>
            <div class="stats-value">¥{{ stats.totalPaymentAmount || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">待审核</div>
            <div class="stats-value">{{ stats.pendingCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已审核</div>
            <div class="stats-value">{{ stats.approvedCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增预收付款</el-button>
      <el-button type="success" @click="handleBatchApprove" :disabled="!selectedIds.length">
        批量审核
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
        批量删除
      </el-button>
      <el-button type="warning" @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
     

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="billNo" label="单据编号" width="150" />
        <el-table-column prop="customerName" label="客户/供应商" width="200" />
        <el-table-column prop="billType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.billType === 'receipt' ? 'success' : 'warning'">
              {{ row.billType === 'receipt' ? '预收款' : '预付款' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="付款方式" width="120">
          <template #default="{ row }">
            {{ renderPaymentMethod(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="billDate" label="单据日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.billDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReceiptList as getAdvanceReceiptList, deleteReceipt as deleteAdvanceReceipt, approveReceipt as approveAdvanceReceipt, batchDeleteReceipt as batchDeleteAdvanceReceipt, batchApproveReceipt as batchApproveAdvanceReceipt, exportReceipt as exportAdvanceReceipt, getReceiptStats as getAdvanceReceiptStats } from '@/api/finance/receipt'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const stats = reactive({
  totalReceiptAmount: '0.00',
  totalPaymentAmount: '0.00',
  pendingCount: 0,
  approvedCount: 0
})

// 统计数据
const totalAdvance = ref(0)

// 搜索表单
const searchForm = reactive({
  customerName: '',
  billType: '',
  paymentMethod: '',
  status: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    
    const response = await getAdvanceReceiptList(params)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else if (response && response.records) {
      // 直接Page格式（兼容性）
      tableData.value = response.records || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取预收付款数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const response = await getAdvanceReceiptStats({})
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const data = response.data
      if (data) Object.assign(stats, data)
      
      // 更新totalAdvance变量
      totalAdvance.value = parseFloat(data?.totalAmount || 0)
    } else if (response && response.totalAmount !== undefined) {
      // 直接数据格式（兼容性）
      Object.assign(stats, response)
      
      // 更新totalAdvance变量
      totalAdvance.value = parseFloat(response.totalAmount || 0)
    } else {
      console.error('统计数据响应格式错误:', response)
      Object.assign(stats, {
        totalAmount: '0.00',
        monthlyAmount: '0.00',
        pendingCount: 0,
        approvedCount: 0
      })
      
      // 重置totalAdvance变量
      totalAdvance.value = 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    Object.assign(stats, {
      totalAmount: '0.00',
      monthlyAmount: '0.00',
      pendingCount: 0,
      approvedCount: 0
    })
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    billType: '',
    paymentMethod: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = () => {
  ElMessage.info('新增预收付款功能待实现')
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看预收付款功能待实现')
}

// 编辑
const handleEdit = (row) => {
  ElMessage.info('编辑预收付款功能待实现')
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条预收付款吗？', '提示', {
      type: 'warning'
    })
    
    const response = await deleteAdvanceReceipt(row.id)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除预收付款失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 审核
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核这条预收付款吗？', '提示', {
      type: 'warning'
    })
    
    await approveAdvanceReceipt(row.id)
    ElMessage.success('审核成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核预收付款失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的预收付款')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条预收付款吗？`, '提示', {
      type: 'warning'
    })
    
    await batchDeleteAdvanceReceipt(selectedIds.value)
    ElMessage.success('批量删除成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除预收付款失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量审核
const handleBatchApprove = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要审核的预收付款')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要审核选中的 ${selectedIds.value.length} 条预收付款吗？`, '提示', {
      type: 'warning'
    })
    
    await batchApproveAdvanceReceipt(selectedIds.value)
    ElMessage.success('批量审核成功')
    loadData()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核预收付款失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出预收付款数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['单据编号', '会员ID', '金额', '单据日期', '状态', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.billNo || '',
        row.memberId || '',
        row.amount || 0,
        row.billDate || '',
        getStatusText(row.status),
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      totalAdvance.value || 0,
      '',
      `记录数: ${pagination.total || 0}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `预收付款数据_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已审核',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

const renderPaymentMethod = (val) => {
  const map = {
    cash: '现金',
    bank: '银行',
    alipay: '支付宝',
    wechat: '微信'
  }
  return map[val] || val || ''
}

// 初始化
onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.advance-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 